# coding=utf-8
import collections
import os
from collections import OrderedDict

import pandas

import gen_down_up2_date
from send_email import send_email_html_a_recent


def traverse_directory(directory):
    res = []
    for root, dirs, files in os.walk(directory):
        for file in files:
            file_path = file
            res.append(file_path)  # 这里可以根据需求对文件路径进行处理
    return res


def get_gen_down_up2_rank20(today_date):
    csv_path = f'result_gen_down_up2/{today_date}_gen_down_up_by_number.csv'
    data_dict = pandas.read_csv(csv_path).to_dict()
    result = {}
    all_date = data_dict.get('日期')
    all_cnt = data_dict.get('总数')
    all_rank = data_dict.get('排名')
    for k, v in all_rank.items():
        if v <= 15:
            result[all_date[k]] = [all_date[k], (0, 0), (v, all_cnt[k])]
    return result


def get_gen_down_up2_today(today_date):
    csv_path = f'result_gen_down_up2/{today_date}_gen_down_up_by_number.csv'
    if not os.path.exists(csv_path):
        stocks = []
        break_days = 5  # 最多计算20个最低点就结束
        cal_date = str(today_date)
        gen_down_up2_date.get_all_stock(stocks, break_days, cal_date)
    if os.path.exists(csv_path):
        data_dict = pandas.read_csv(csv_path).to_dict()
        all_date = data_dict.get('日期')
        all_cnt = data_dict.get('总数')
        all_rank = data_dict.get('排名')
        for k, v in all_date.items():
            if v == today_date:
                return (all_rank[k], all_cnt[k])
    return (0, 0)


if __name__ == '__main__':
    files = traverse_directory('result_a_recent_low_up')
    d = collections.defaultdict(list)
    all_date = []
    for f in files:
        if str(f).endswith('.txt'):
            continue
        f_arr = f.split('_')
        try:
            s = eval(f_arr[-1].split('.')[0])
        except Exception as e:
            continue
        date_int = eval(f_arr[0])
        all_date.append(date_int)
        d[s].append(date_int)

    sorted_items = sorted(d.items(), key=lambda x: x[0], reverse=True)
    sorted_dict = OrderedDict(sorted_items)

    today_date = max(all_date)
    rank_top20 = get_gen_down_up2_rank20(today_date)
    rank_top20_dates = list(rank_top20.keys())

    result_dict = {}
    cnt = 0
    rank = 0
    today_cnt = 0
    send_em = False
    for k, v in sorted_dict.items():
        cnt += 1
        if today_date in v:
            send_em = True
            rank = cnt
            today_cnt = k
            color = 1
            result_dict[v[0]] = [today_date, (cnt, k), (0, 0)]
            break
        else:
            color = 0
        if k > 100:
            result_dict[v[0]] = [v[0], (cnt, k), (0, 0)]

    for k, v in result_dict.items():
        if k in rank_top20:
            rank_top20[k][0] = v[0]
            rank_top20[k][1] = v[1]
        else:
            rank_top20[k] = [v[0], v[1], (0, 0)]

    result_arr = list(rank_top20.values())
    result_arr2 = sorted(result_arr, key=lambda x: x[0], reverse=True)
    result_arr3 = []
    for idx, item in enumerate(result_arr2[:11]):
        date, t1, t2 = item
        temp_t2 = get_gen_down_up2_today(date)
        result_arr3.append([date, t1, temp_t2])
    if send_em:
        title = f'{today_date}_{today_cnt}_rank_{rank}_a_recent_low_up_ana'
        send_email_html_a_recent.send_html(result_arr3, title)
